import {CameraControls, PerspectiveCamera} from '@react-three/drei'
import {useEffect, useRef} from 'react'
import {useFrame, useThree} from '@react-three/fiber'
import * as THREE from 'three'

export const CustomCameraControls = ({players, ...props}) => {
  const controls = useRef()
  const cameraRef = useRef()
  const {pos = [0, 0, 0], target = [0, 0, 0]} = props

  const vp = useThree((state) => state.viewport)


  const adjustCamera = () => {
    const currVP = vp.getCurrentViewport(
      cameraRef.current, new THREE.Vector3(0, 0, 0))
    const dist_factor = 10 / currVP.width
    controls.current?.setLookAt(
      pos[0] * dist_factor,
      pos[1] * dist_factor,
      pos[2] * dist_factor,
      target[0], target[1], target[2],
      true)
      .then(() => {
      })
  }

  useEffect(() => {
    adjustCamera()
  }, [players])

  useEffect(() => {
    const onResize = () => {
      adjustCamera()
    }
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])

  useFrame(({clock}) => {
    controls.current.camera.position.x +=
      Math.cos(clock.getElapsedTime() * 0.5) * 0.25
    controls.current.camera.position.y +=
      Math.sin(clock.getElapsedTime() * 1) * 0.125
  })

  return (
    <>
      <PerspectiveCamera ref={cameraRef} position={[0, 1, 10]}/>
      <CameraControls ref={controls}/>
    </>
  )
}
